package com.right.near.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * hash表序号
 *
 * @author: star
 * @date: 2020-10-13
 */
@Slf4j
public class HashUtil {

    private static long hash64A(ByteBuffer buf, int seed) {
        ByteOrder byteOrder = buf.order();
        buf.order(ByteOrder.LITTLE_ENDIAN);
        long m = 0xc6a4a7935bd1e995L;
        int r = 47;
        long h = seed ^ (buf.remaining() * m);
        long k;
        while (buf.remaining() >= 8) {
            k = buf.getLong();
            k *= m;
            k ^= k >>> r;
            k *= m;
            h ^= k;
            h *= m;
        }
        if (buf.remaining() > 0) {
            ByteBuffer finish = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
            finish.put(buf).rewind();
            h ^= finish.getLong();
            h *= m;
        }
        h ^= h >>> r;
        h *= m;
        h ^= h >>> r;
        buf.order(byteOrder);
        return h;
    }

    /**
     * 描述：hash值生成
     *
     * @param key
     * @return
     */
    private static long hash(byte[] key) {
        return hash64A(ByteBuffer.wrap(key), 0x1234ABCD);
    }

    /**
     * 根据设备号码获取轨迹表讯号
     *
     * @param deviceNo
     * @return
     */
    public static Integer getTableNo(Long deviceNo) {
        Long no = null;
        if (Objects.nonNull(deviceNo)) {
            byte[] bytes;
            bytes = deviceNo.toString().getBytes(StandardCharsets.UTF_8);
            no = Math.abs(hash(bytes) % 256) + 1;
        }
        return Objects.isNull(no) ? null : no.intValue();
    }

}
